from PIL import Image, ImageDraw, ImageFont
import math, datetime
import time, tkinter as tk
from tkinter import filedialog
from PyQt5.QtGui import QPixmap
from pyqt5_plugins.examplebutton import QtWidgets
from form import Ui_MainWindow


def get_guoqitouxiang(touxiang_img, guoqi_img):
    '''
    这个函数可以完成头像与国旗的渐变融合，返回一个img对象
    '''
    key = 3.2  # 修改key值可以调整国旗的范围，推荐2~4之间的数字，支持小数
    motherland_flag = Image.open(guoqi_img)
    head_picture = Image.open(touxiang_img)
    # 截图国旗上的五颗五角星
    flag_width, flag_height = motherland_flag.size
    crop_flag = motherland_flag.crop((66, 0, flag_height + 66, flag_height))
    # 将国旗截图处理成颜色渐变
    for i in range(flag_height):
        for j in range(flag_height):
            color = crop_flag.getpixel((i, j))
            distance = int(math.sqrt(i * i + j * j))
            alpha = 255 - int(distance // key)
            new_color = (*color[0:-1], alpha if alpha > 0 else 0)
            crop_flag.putpixel((i, j), new_color)
    # 修改渐变图片的尺寸，适应头像大小，粘贴到头像上
    new_crop_flag = crop_flag.resize(head_picture.size)
    head_picture.paste(new_crop_flag, (0, 0), new_crop_flag)
    # head_picture.save('国旗头像.png')
    return head_picture


def plus_word(touxiang_img, guoqi_img):
    '''

    这个函数可以实现在图片上写入文字，文字的颜色、大小，位置可以自行设置
    '''

    head_picture = get_guoqitouxiang(touxiang_img, guoqi_img)
    # 设置字体，如果没有，也可以不设置,通过修改这里的数字大小，改变文字的大小

    # head_picture.show()
    now = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
    head_picture.save(f'国旗渐变头像.png')
    print('头像保存成功')


def sel_file():
    root = tk.Tk()
    root.withdraw()
    Filepath = filedialog.askopenfilename()
    ui.label.setText(Filepath)
    return Filepath


def start():
    path = ui.label.text()
    print(path)
    # touxiang = 'img.png'
    touxiang = path
    guoqi = '国旗1024.png'
    print('-----------------------开始执行-----------------------')
    start = time.time()
    plus_word(touxiang, guoqi)
    end = time.time()
    print(f'执行结束，用时{end - start}秒')
    pixmap = QPixmap('国旗渐变头像.png')
    ui.label_2.setPixmap(pixmap)
    ui.label_2.setScaledContents(True)


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    ui.pushButton.clicked.connect(sel_file)
    ui.pushButton_2.clicked.connect(start)
    MainWindow.show()
    sys.exit(app.exec_())
